package com.zj.musicTools

import android.app.Activity
import android.content.Context
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.webkit.ValueCallback
import android.webkit.WebResourceError
import android.webkit.WebSettings
import android.webkit.WebView
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.view.WindowInsetsControllerCompat
import androidx.lifecycle.MutableLiveData
import com.google.accompanist.insets.ProvideWindowInsets
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import com.zj.musicTools.function.AgentStation
import com.zj.musicTools.function.PermissionPage
import com.zj.musicTools.page.NavigationPage
import com.zj.musicTools.ui.theme.MusicToolsTheme


class MainActivity : ComponentActivity() {
    /*private val viewModel by lazy{
        ViewModelProvider(this).get(myViewModel::class.java)
    }*/
    companion object{
        val Agent = AgentStation
        lateinit var CONTEXT: Context
        lateinit var mainInstant:MainActivity
        val resultData: MutableLiveData<List<Uri>> = MutableLiveData()
    }
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        viewModel.position.observe(this, Observer{ newTab: CourseTabs ->  })
        setContent {
//            ProvideWindowInsets(content = { NavigationPage() })
            ProvideWindowInsets {
                MusicToolsTheme {
                    // A surface container using the 'background' color from the theme
                    Surface(
                        modifier = Modifier.fillMaxSize(),
                        color = MaterialTheme.colorScheme.background
                    ) {
                        CONTEXT=this
                        mainInstant=this
                        transparentStatusBar()
                        PermissionPage()
                        NavigationPage()
                    }
                }
            }


        }

    }
    /*  @SuppressLint("SetJavaScriptEnabled")
      private fun setWebSettings() {
          val webSettings = webView.settings
          //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
          webSettings.javaScriptEnabled = true
          //设置自适应屏幕，两者合用
          webSettings.useWideViewPort = true //将图片调整到适合webview的大小
          webSettings.loadWithOverviewMode = true // 缩放至屏幕的大小
          //缩放操作
          webSettings.setSupportZoom(true) //支持缩放，默认为true。是下面那个的前提。
          webSettings.builtInZoomControls = true //设置内置的缩放控件。若为false，则该WebView不可缩放
          webSettings.displayZoomControls = false //隐藏原生的缩放控件

          webSettings.domStorageEnabled = true // 开启 DOM storage API 功能

          //其他细节操作
          webSettings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK //关闭webview中缓存
          webSettings.allowFileAccess = true //设置可以访问文件
          webSettings.javaScriptCanOpenWindowsAutomatically = true //支持通过JS打开新窗口
          webSettings.loadsImagesAutomatically = true //支持自动加载图片
          webSettings.defaultTextEncodingName = "UTF-8"//设置编码格式
      }*/
    private fun initObserver(){
        Log.d("WebViewCtrl", "initObserver")
        resultData.observe(mainInstant){
            Log.d("WebViewCtrl", "observe: $it")
            uploadMessageAboveL?.onReceiveValue(it.toTypedArray())
        }
    }
    private var uploadMessageAboveL: ValueCallback<Array<Uri>>? =null

    /*inner class ProgressWebViewChromeClient:WebChromeClient(){
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            progressBar.progress=newProgress
        }

    }
    override fun onReceivedTitle(view:WebView?,title:String?){
        super.onReceivedTitle(view,title)
    }*/
    @Composable
    fun CustomWebView(modifier: Modifier = Modifier,
        //网络请求地址
                      url:String,
        //自己处理返回事件
                      onBack: (webView: WebView?) -> Unit,
        //自己选择是否接收，网页地址加载进度回调
                      onProgressChange: (progress:Int)->Unit = {},
        //自己选择是否设置自己的WebSettings配置
                      initSettings: (webSettings: WebSettings?) -> Unit = {},
        //自己选择是否处理onReceivedError回调事件
                      onReceivedError: (error: WebResourceError?) -> Unit = {}){}



}


/**
 * 设置透明状态栏
 *
 * 深色模式的uiMode值为:0x21
 * 浅色模式的uiMode值为:0x11
 */
@Composable
fun Activity.transparentStatusBar() {
    val controller = WindowInsetsControllerCompat(window,window.decorView)
    val systemUiController = rememberSystemUiController()
    val useDarkIcons = !isSystemInDarkTheme()
    val topcolor=colorResource(id = R.color.white)


//    ViewCompat.getWindowInsetsController(window.decorView)

    // 隐藏状态栏
//    controller.hide(statusBars())

    //状态栏反色
//    controller.isAppearanceLightStatusBars = resources.configuration.uiMode != 0x21

    // 设置状态栏颜色为透明
//    window.statusBarColor = Color.TRANSPARENT

    SideEffect {
        // 设置状态栏颜色
        systemUiController.setStatusBarColor(
            color = topcolor,
            darkIcons = useDarkIcons
        )
    }

}



@Preview(showBackground = true)
@Composable
private fun DefaultPreview() {
    MusicToolsTheme {
//        Greeting("Android")
    }
}

/**
 * 后期：
 * 1.利用testLeader项目界面构建app，分为 转换(主页)，日志，设置 三个页面
 * 2.学习安卓app本地数据保存方法，将设置保存到本地，将返回的josn数据解析后加上 日期-时间 前缀，写到app目录的 *.log中
 * 3.设置界面加入实用用功能：打开输出目录，一键打开各大音乐app的默认目录 按钮
 * 4.将jni调用移植到jniHandler类
 *
 * kotlin调用json：
 * https://cloud.tencent.com/developer/article/2055933
 * https://blog.csdn.net/qq_45488901/article/details/120534976
 * */